#include "head.h"

int tcp_init(int *socket_fd, char *ip, char *port)
{
    *socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in sock_addr;
    sock_addr.sin_family = AF_INET;
    sock_addr.sin_port = htons(atoi(port));
    sock_addr.sin_addr.s_addr = inet_addr(ip);

    int reuse = 1;
    setsockopt(*socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));

    int ret = bind(*socket_fd, (struct sockaddr *)&sock_addr, sizeof(sock_addr));
    ERROR_CHECK(ret, -1, "bind in tcp.c:");
    ret = listen(*socket_fd, 1000);
    ERROR_CHECK(ret, -1, "listen in tcp.c");
    return 0;
}

// 这个结构体只是在recv_train和send_train函数中使用过
typedef struct train_s{
    int length;
    char buf[4096];
}train_t;

int recv_train(char* buf, int net_fd){
    train_t train;
    bzero(&train,sizeof(train));
    int ret = recv(net_fd, &(train.length), sizeof(train.length),MSG_WAITALL);
    ERROR_CHECK(ret,-1,"recvTrain 1 in tcp.c");
    //对端关闭连接
    if(ret == 0){
        return 0;
    }
    ret = recv(net_fd,train.buf,train.length,MSG_WAITALL);
    ERROR_CHECK(ret,-1,"recvTrain 2 in tcp.c");
    //对端关闭连接
    if(ret == 0){
        return 0;
    }

    strcpy(buf,train.buf);
    return ret;
}
int send_train(char* buf, int net_fd){
    train_t train;
    bzero(&train,sizeof(train));
    strcpy(train.buf,buf);
    train.length = strlen(train.buf);

    int ret = send(net_fd,&(train.length),sizeof(train.length),MSG_NOSIGNAL);
    ERROR_CHECK(ret,-1,"sendTrain 1 in tcp.c");
    ret = send(net_fd,train.buf,train.length,MSG_NOSIGNAL);
    ERROR_CHECK(ret,-1,"sendTrain 2 in tcp.c");
}
